package ws.jdbc.concurrent.cursor;

import java.sql.ResultSet;
import java.sql.SQLException;
import ws.jdbc.concurrent.exception.JdbcConcurrentException;

/**
 * Implementation of the {@link ICursorFactory} services.
 *
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
public class CursorFactoryImpl implements ICursorFactory {

  /** Result set that the created cursors will work upon. */
  private ResultSet rs;

  /**
   * Create a new instance.
   *
   * @param rs result set that the created cursors will work upon.
   */
  public CursorFactoryImpl(ResultSet rs) {
    this.rs = rs;
  }

  /**
   * {@inheritDoc}
   */
  public ICursorForwardReadOnly createForwardRead() throws SQLException, JdbcConcurrentException {
    if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {
      throw new JdbcConcurrentException(JdbcConcurrentException.IS_NOT_SCROLLABLE);
    }
    if (rs.getConcurrency() != ResultSet.CONCUR_READ_ONLY) {
      throw new JdbcConcurrentException(JdbcConcurrentException.IS_NOT_READ_ONLY);
    }
    return new CursorForwardReadOnly(rs);
  }

  /**
   * {@inheritDoc}
   */
  public ICursorForwardUpdate createForwardUpdate() throws SQLException, JdbcConcurrentException {
    if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {
      throw new JdbcConcurrentException(JdbcConcurrentException.IS_NOT_SCROLLABLE);
    }
    if (rs.getConcurrency() != ResultSet.CONCUR_UPDATABLE) {
      throw new JdbcConcurrentException(JdbcConcurrentException.IS_NOT_READ_ONLY);
    }
    return new CursorForwardUpdate(rs);
  }

  /**
   * {@inheritDoc}
   */
  public final ICursorScrollReadOnly createScrollRead() throws SQLException, JdbcConcurrentException {
    if (rs.getType() == ResultSet.TYPE_FORWARD_ONLY) {
      throw new JdbcConcurrentException(JdbcConcurrentException.IS_NOT_SCROLLABLE);
    }
    if (rs.getConcurrency() != ResultSet.CONCUR_READ_ONLY) {
      throw new JdbcConcurrentException(JdbcConcurrentException.IS_NOT_READ_ONLY);
    }
    return new CursorScrollReadOnly(rs);
  }

  /**
   * {@inheritDoc}
   */
  public ICursorScrollUpdate createScrollUpdate() throws SQLException, JdbcConcurrentException {
    if (rs.getType() == ResultSet.TYPE_FORWARD_ONLY) {
      throw new JdbcConcurrentException(JdbcConcurrentException.IS_NOT_SCROLLABLE);
    }
    if (rs.getConcurrency() != ResultSet.CONCUR_UPDATABLE) {
      throw new JdbcConcurrentException(JdbcConcurrentException.IS_NOT_READ_ONLY);
    }
    return new CursorScrollUpdate(rs);
  }
}
